<template>
  <q-input
    :label="label"
    :style="{ width: width + 'px', height: '40px' }"
    @clear="onClear"
    autocomplete="off"
    clearable
    dense
    filled
    ref="input"
    v-model="triggerModel"
  >
    <q-popup-proxy @keyup.enter="onConfirm" v-model="open">
      <div class="q-pa-md q-gutter-md">
        <q-input autofocus filled v-model="popupModel" :placeholder="`输入${label}`" />
        <div>
          <q-btn class="full-width" color="primary" label="确认" @click="onConfirm" />
        </div>
      </div>
    </q-popup-proxy>
  </q-input>
</template>

<script lang="ts">
import { emitter } from 'src/emitter';
import { defineComponent, ref } from 'vue';
import { composeEqualClause, composeLikeClause } from './utils';

export default defineComponent({
  name: 'search-input',

  props: {
    label: {
      type: String,
      required: true,
    },
    field: {
      type: String,
      required: true,
    },
    id: {
      type: String,
    },
    width: {
      type: Number,
      default: 200,
    },
    prefix: {
      type: String,
      default: '',
    },
    like: {
      type: Boolean,
    },
  },

  setup(props) {
    const open = ref(false);
    const triggerModel = ref('');
    const popupModel = ref('');

    const onConfirm = () => {
      if (!popupModel.value) {
        return;
      }
      let clause = '';
      if (props.like) {
        clause = composeLikeClause(props.prefix, props.field, popupModel.value);
      } else {
        clause = composeEqualClause(props.prefix, props.field, popupModel.value);
      }
      open.value = false;
      triggerModel.value = popupModel.value;
      emitter.emit('table_search', { id: props.id, field: props.field, clause });
    };

    const onClear = () => {
      triggerModel.value = '';
      popupModel.value = '';
      emitter.emit('table_search', { id: props.id, field: props.field });
    };

    return { popupModel, triggerModel, onClear, onConfirm, open };
  },
});
</script>
